package com.qa.controller;

import com.github.pagehelper.PageInfo;
import com.qa.common.Const;
import com.qa.common.ServerResponse;
import com.qa.pojo.Download;
import com.qa.pojo.User;
import com.qa.service.IDownloadService;
import com.qa.service.IFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @Author
 * @Date 2020/3/11 22:03
 * @Desc
 **/
@Controller
public class DownloadController {

    @Autowired
    private IDownloadService downloadService;
    @Autowired
    private IFileService fileService;


    @GetMapping("/download/page")
    public String downloadPage(Model model,@RequestParam(value = "downloadName", required = false) String downloadName,
                               @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                               @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        PageInfo<Download> pageInfo = downloadService.getAll(downloadName, pageNum, pageSize);
        model.addAttribute("pageInfo", pageInfo.getList());
        return "download";
    }

    @GetMapping("/my/download/page")
    public String myDownloadPage(HttpServletRequest request, Model model) {
        User user = (User) request.getSession().getAttribute(Const.CURRENT_USER);
        List<Download> downloads = downloadService.getByEmail(user.getEmail());
        model.addAttribute("downloads", downloads);
        return "myDownload";
    }

    @PostMapping("/my/download/upload")
    @ResponseBody
    public ServerResponse downloadUpload(Download download, HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute(Const.CURRENT_USER);
        return downloadService.upload(download, user);
    }


    @GetMapping("/download/file")
    public void downloadFile(@RequestParam("downloadId") Integer downloadId, HttpServletResponse response) throws IOException {
        Download download = downloadService.getById(downloadId);
        List<File> files = new ArrayList<File>();
        files.add(new File(Const.DOWNLOAD_PATH + download.getPath()));
        // 拼接压缩文件名
        String reportNameZip = download.getPath() + ".ZIP";
        response.setContentType("APPLICATION/OCTET-STREAM");
        // 设置头解决乱码
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(reportNameZip, "UTF-8"));
        ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
        File[] filess = new File[files.size()];
        for (int i = 0; i < files.size(); i++) {
            filess[i] = files.get(i);
        }
        zipFile(filess, "", zos);
        zos.flush();
        zos.close();
        for (int i = 0; i < filess.length; i++) {
            filess[i].delete();
        }
    }


    public static void zipFile(File[] subs, String baseName, ZipOutputStream zos) throws IOException {
        for (int i = 0; i < subs.length; i++) {
            File f = subs[i];
            zos.putNextEntry(new ZipEntry(baseName + f.getName()));
            FileInputStream fis = new FileInputStream(f);
            byte[] buffer = new byte[1024];
            int r = 0;
            while ((r = fis.read(buffer)) != -1) {
                zos.write(buffer, 0, r);
            }
            fis.close();
        }
    }


    @GetMapping("/my/download/deleteById")
    @ResponseBody
    public ServerResponse deleteDownloadById(@RequestParam("downloadId") Integer downloadId) {
        return  downloadService.deleteById(downloadId);
    }

    @GetMapping("/download/search")
    public String downloadSearch(@RequestParam("keyword") String keyword, Model model) {
        List<Download> pageInfo = downloadService.getAllDownload(keyword);
        model.addAttribute("pageInfo", pageInfo);
        return "download";
    }

}
